package com.buddy.spring.boot.service;

import com.alibaba.fastjson.JSON;
import com.buddy.spring.boot.dao.entity.SysPermission;
import com.buddy.spring.boot.dao.mapper.SysPermissionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author buddy
 * @date 2021/10/28
 */
@Service
@Transactional(rollbackFor = Throwable.class)
@Slf4j
public class SysPermissionService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysPermissionServiceB sysPermissionServiceB;

    public void copy() {
        List<SysPermission> list = sysPermissionMapper.select(s -> s);
        log.info(JSON.toJSONString(list));
        list.forEach(sysPermission -> {
            sysPermissionMapper.deleteByPrimaryKey(sysPermission.getId());
            sysPermissionServiceB.copyItem(sysPermission, sysPermission.getId());
        });
        List<SysPermission> list2 = sysPermissionMapper.select(s -> s);
        log.info(JSON.toJSONString(list2));
    }

    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
    public void copyItem(SysPermission sysPermission, Long id) {
        SysPermission sysPermission1 = new SysPermission();
        sysPermission1.setSysPermission(sysPermission.getSysPermission());
        sysPermissionMapper.insertSelective(sysPermission1);
        List<SysPermission> list2 = sysPermissionMapper.select(s -> s);
        log.info(JSON.toJSONString(list2));
        if (id % 2 == 1) {
            throw new RuntimeException("error");
        }
    }
}
